<template>
  <nav class="bg-white shadow-md p-4 flex justify-between items-center flex-wrap">
    <!-- Logo -->
    <router-link
      to="/bills"
      class="flex items-center space-x-2 text-blue-600 font-semibold text-xl"
      @click="menuOpen = false"
    >
      <span>📒 记账应用</span>
    </router-link>

    <!-- 移动端菜单按钮 -->
    <button class="md:hidden text-gray-600" @click="toggleMenu">
      <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none"
           viewBox="0 0 24 24" stroke="currentColor">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
              d="M4 6h16M4 12h16M4 18h16"/>
      </svg>
    </button>

    <!-- 菜单项 -->
    <div
      :class="[
        'w-full md:flex md:items-center md:space-x-6 md:w-auto',
        menuOpen ? 'block' : 'hidden'
      ]"
      class="mt-4 md:mt-0 space-y-2 md:space-y-0"
    >
      <router-link
        to="/bills"
        class="block transition font-medium px-2 py-1 rounded"
        :class="isActive('/bills') ? 'text-blue-600 bg-blue-100 font-bold' : 'text-gray-700 hover:text-blue-600'"
        @click="menuOpen = false"
      >
        账单列表
      </router-link>
      <router-link
        to="/add"
        class="block transition font-medium px-2 py-1 rounded"
        :class="isActive('/add') ? 'text-blue-600 bg-blue-100 font-bold' : 'text-gray-700 hover:text-blue-600'"
        @click="menuOpen = false"
      >
        添加账单
      </router-link>
      <router-link
        to="/charts"
        class="block transition font-medium px-2 py-1 rounded"
        :class="isActive('/charts') ? 'text-blue-600 bg-blue-100 font-bold' : 'text-gray-700 hover:text-blue-600'"
        @click="menuOpen = false"
      >
        图表分析
      </router-link>
      <button
        @click="logout"
        class="block text-red-500 hover:text-red-600 font-medium transition"
      >
        退出登录
      </button>
    </div>
  </nav>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()
const menuOpen = ref(false)

const toggleMenu = () => {
  menuOpen.value = !menuOpen.value
}

// 判断当前菜单是否高亮
const isActive = (path: string) => {
  // 如果页面路径等于path或以path开头（支持/bills/xxx等子路由高亮）
  return route.path === path || route.path.startsWith(path + '/')
}

const logout = () => {
  localStorage.removeItem('user_id')
  router.push('/')
}
</script>
